package com.dana.clientdemo

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.os.IBinder
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import com.dana.clientdemo.ui.theme.ClientDemoTheme
import com.dana.clientdemo.utils.BitmapUtils
import com.dana.safeluckbdface_recong.IBDAidlInterface
import com.dana.safeluckbdface_recong.IBDCallback
import com.dana.safeluckbdface_recong.User
import kotlinx.coroutines.launch
import java.io.File


class MainActivity : ComponentActivity(){
    private val TAG = "MainActivity"
    val SERVER_APP = "com.dana.safeluckbdface_recong"
    val CLASS_STR = "com.dana.safeluckbdface_recong.BDRecongService"
    private var iBdFaceAidlFace:IBDAidlInterface?=null
    private val viewModel:MyViewModel  by viewModels()

    private val callback = object : IBDCallback.Stub() {
        override fun onResultInfo(type: Int, code: Int, message: String?, user: User?) {
            Log.i(TAG,"type=$type,code=$code,message=$message,user=${user?.userName}")
        }


    }
    val serviceConn = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.i(TAG,"客户端绑定服务成功，线程=${Thread.currentThread().name}")
            iBdFaceAidlFace = IBDAidlInterface.Stub.asInterface(service)
            iBdFaceAidlFace?.registerBDCallback(callback)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            //正常的解绑永远都不会走到这个onServiceDisconnected方法 ；
            //异常情况下，会走到这个方法（网上查的）
            iBdFaceAidlFace?.unRegisterBDCallback(callback)
            Log.i(TAG,"客户端解绑服务成功，线程=${Thread.currentThread().name}")
            iBdFaceAidlFace = null
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        val intent = Intent()
        intent.component = ComponentName(SERVER_APP,CLASS_STR)
        bindService(intent,serviceConn, Context.BIND_AUTO_CREATE)
        lifecycleScope.launch {
            Log.i(TAG,"lifecycleScope.launch")
            viewModel.viewEvents.collect{
                when(it){
                    is MyViewModel.MainViewEvents.SendBitmapEvent ->{
                        Log.i(TAG,"发送图片事件,线程=${Thread.currentThread().name}")
                        val bmp =  BitmapFactory.decodeFile(
                            Environment.getExternalStorageDirectory().absolutePath + File.separator
                                +"camera/10:01:26_1051.png");
                        var user = iBdFaceAidlFace?.sendBitmap(BitmapUtils.bitmapToBytes(bmp),"10:01:26_1051.png")
                        Log.i(TAG,"接收结果=${user?.userName},线程=${Thread.currentThread().name}")
                    }
                    is MyViewModel.MainViewEvents.UnbindEvent ->{
                        Log.i(TAG,"解绑服务,线程=${Thread.currentThread().name}")
                        iBdFaceAidlFace?.unRegisterBDCallback(callback)
                        unbindService(serviceConn)
                        iBdFaceAidlFace = null
                    }
                    is MyViewModel.MainViewEvents.BindEvent ->{
                        Log.i(TAG,"绑定服务,线程=${Thread.currentThread().name}")
                        bindService(intent,serviceConn, Context.BIND_AUTO_CREATE)
                    }
                    is MyViewModel.MainViewEvents.InitBDEvent ->{
                        Log.i(TAG,"初始化,线程=${Thread.currentThread().name}")
                        var s = iBdFaceAidlFace?.initBD("BYEI-RSRT-XZWO-JIOC")
                        Log.i(TAG,"初始化,结果=$s,线程=${Thread.currentThread().name}")
                    }
                    is MyViewModel.MainViewEvents.ImportBitmapEvent ->{
                        Log.i(TAG,"导入图片,线程=${Thread.currentThread().name}")
                        val dirPath = Environment.getExternalStorageDirectory().absolutePath+File.separator+"Face-Import"

                        iBdFaceAidlFace?.importPictures(dirPath)

                    }
                    is MyViewModel.MainViewEvents.StartActivityEvent ->{
                        val intent = Intent(Intent.ACTION_MAIN)
                        intent.addCategory(Intent.CATEGORY_LAUNCHER)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                        intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.devecent.bumblebee_km3/.activity.LoadingActivity}

                        intent.setComponent(ComponentName("com.devecent.bumblebee_km3",
                                "com.devecent.bumblebee_km3.activity.LoadingActivity"))
                        applicationContext.startActivity(intent)
                    }
                    else ->{

                    }
                }
            }
        }
        setContent {
            ClientDemoTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding),
                        viewModel = viewModel
                    )
                }
            }
        }
    }



}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier,viewModel: MyViewModel) {
    Column {
        Text(
            text = "Hello $name!",
            modifier = modifier,

            )

        Button(onClick = {
            viewModel.dispatchEvents(MyViewModel.MainViewActions.InitBDAction)
            Log.i("Dana","初始.....")
        }){
            Text("初始化")
        }
        Button(onClick = {
            viewModel.dispatchEvents(MyViewModel.MainViewActions.ImportBitmapsAction)
            Log.i("Dana","导入图片.....")
        }){
            Text("导入图片")
        }
        Button(onClick = {
            viewModel.dispatchEvents(MyViewModel.MainViewActions.SendBitmapAction)
            Log.i("Dana","发送图片.....")
        }){
            Text("发送图片")
        }

        Button(onClick = {
            viewModel.dispatchEvents(MyViewModel.MainViewActions.BindServiceAction)
        }){
            Text("绑定服务")
        }
        Button(onClick = {
            viewModel.dispatchEvents(MyViewModel.MainViewActions.UnbindServiceAction)
        }){
            Text("解绑服务")
        }
        Button(onClick = {viewModel.dispatchEvents(MyViewModel.MainViewActions.StartActAction)}){
            Text("打开应用")
        }
    }

}

